<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 公共组件 -->
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template #after>
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportData">导出</el-button>
          <el-button size="small" type="danger" @click="exportData2">导出复杂表头</el-button>
          <el-button size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table v-loading="loading" border :data="list">
          <el-table-column type="index" label="序号" sortable="" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column width="120" label="头像" sortable="" prop="staffPhoto">
            <template slot-scope="{ row }">
              <!-- <img v-imagerro="img" :src="row.staffPhoto" class="userPic" alt="" @click="showQrCode(row.staffPhoto)"> -->

              <el-image
                class="userPic"
                title="查看图片"
                :src="row.staffPhoto"
                fit="cover"
                style=" cursor: pointer;"
                @click="showQrCode(row.staffPhoto)"
              >
                <img slot="error" title="查看图片" class="userPic" src="@/assets/common/bigUserHeader.png" alt="" @click="showQrCode(row.staffPhoto)">
              </el-image>

            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <!--格式化聘用形式 -->
          <el-table-column
            label="聘用形式"
            sortable=""
            prop="formOfEmployment"
            :formatter="formatEmployment"
          />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <!-- 作用域插槽 -->
            <template slot-scope="{ row }">{{ row.timeOfEntry | formatDate }}</template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template slot-scope="{ row }">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" :disabled="!checkPermission('POINT-USER-DELETE')" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">

          <el-pagination
            layout="prev, pager, next"
            :total="page.total"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
      <!-- 新曾员工弹窗 -->
      <add-employee :show-dialog.sync="showDialog" />
      <!-- 二维码弹窗 -->
      <el-dialog title="二维码" :visible.sync="showCodeDialog">
        <el-row class="erweima">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!--分配角色弹窗 -->
      <assign-role
        ref="assignRole"
        :show-role-dialog.sync="showRoleDialog"
        :user-id="userId"
      />
    </div>
  </div>
</template>

<script>
import { getEmployeeList } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import { delEmployee } from '@/api/employees'
import AddEmployee from './components/add-employee.vue'
import { formatDate } from '@/filters'
// 转二维码插件
import QrCode from 'qrcode'
import AssignRole from './components/assign-role.vue'
export default {
  name: 'Employees',
  components: { AddEmployee, AssignRole },
  props: {},
  data () {
    return {
      list: [],
      loading: false,
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      showDialog: false,
      img: require('@/assets/common/bigUserHeader.png'),
      showCodeDialog: false,
      showRoleDialog: false, // 分配角色弹窗状态
      userId: ''
    }
  },
  computed: {},
  watch: {},
  created () {
    this.getEmployeeList()
  },
  mounted () {},
  methods: {
    async changePage (newPage) {
      this.page.page = newPage
      this.getEmployeeList()
    },
    // TAG 获取员工的综合列表
    async getEmployeeList () {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows
      if (rows.length) {
        this.page.page++
      }
      this.loading = false
    },
    // 格式化聘用形式
    formatEmployment (row, column, cellValue, index) {
      // 要去找 1所对应的值
      const obj = EmployeeEnum.hireType.find(item => item.id === +cellValue)
      return obj ? obj.value : '未知'
    },
    // TAG 删除员工
    async delEmployee (id) {
      try {
        await this.$confirm('您确定删除该员工吗', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
        await delEmployee(id)
        this.getEmployeeList()
        this.$message.success('删除员工成功')
      } catch (err) {
        console.log(err)
      }
    },
    // TAG 导出excel数据
    exportData () {
      //  做操作
      // 懒加载
      // 表头对应关系
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }

      import('@/vendor/Export2Excel').then(async excel => {
        // page: this.page.total 的目的是要一次性把全部的员工列表查询出来
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        // [["张三", "13811111111"，"2018","1", "2018", "10002"],["李思", "13911111111"，"2018","1", "2018", "10002"],...]
        const data = this.formatJson(headers, rows)

        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: '员工信息表',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    // TAG 导出复杂表头
    exportData2 () {
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 导出excel
      import('@/vendor/Export2Excel').then(async excel => {
        //  excel是引入文件的导出对象
        // 导出  header从哪里来
        // data从哪里来
        // 现在没有一个接口获取所有的数据
        // 获取员工的接口 页码 每页条数    100   1 10000
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        const data = this.formatJson(headers, rows) // 返回的data就是 要导出的结构
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: '员工资料表',
          multiHeader, // 复杂表头
          merges // 合并选项
        })
      })
    },
    // 该方法负责将数组转化成二维数组并转为中文
    formatJson (headers, rows) {
      // 首先遍历数组
      //  [{ username: '张三', mobile: '13811111111', ...},{},{}]  => [[’张三', '13811111111',...],[],[]]
      return rows.map(item => {
        // Object.keys(headers) => ['姓名','手机号',...]
        return Object.keys(headers).map(key => {
          // 处理时间
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            // TAG 此时需要转换时间格式
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            // 转换聘用形式 对应的文字
            const obj = EmployeeEnum.hireType.find(obj => obj.id === item[headers[key]])
            return obj ? obj.value : '未知'
          }
          return item[headers[key]]
        })
      })
    },
    // 点击头像
    showQrCode (img) {
      try {
        if (img.length > 10) {
          this.showCodeDialog = true
          // 因为dom是异步渲染
          this.$nextTick(() => {
            QrCode.toCanvas(this.$refs.myCanvas, img)
          })
        } else {
          this.$message.warning('用户还没有上传头像')
        }
      } catch (err) {
        this.$message.warning('用户还没有上传头像')
      }
    },
    // 点击角色
    async editRole (userId) {
      this.userId = userId
      // 父组件调用子组件方法，保证拿到当前用户拥有的角色id，防止出现闪动
      await this.$refs.assignRole.getUserDetailById(userId)
      this.showRoleDialog = true
    }

  }
}
</script>

<style scoped lang="scss">
.employees-container {
  .el-row--flex.is-justify-center{
    justify-content:end;
    margin-right: 40px;
  }
  .userPic{
    width: 65px;
    height: 65px;
    border-radius: 65px;
  }
 ::v-deep .el-table__body-wrapper  .cell {
      text-align: center;
  }
  ::v-deep .el-table--border th, .el-table__fixed-right-patch{
    text-align: center;
  }
}
.erweima{
  display: flex;
  justify-content: center;
  align-items: center;

}
</style>
